package com.atguigu.daijia.customer.service.impl;

import com.atguigu.daijia.common.constant.RedisConstant;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.loginCheck.LoginCheck;
import com.atguigu.daijia.common.result.Result;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.common.util.AuthContextHolder;
import com.atguigu.daijia.common.util.JwtUtil;
import com.atguigu.daijia.customer.client.CustomerInfoFeignClient;
import com.atguigu.daijia.customer.service.CustomerService;
import com.atguigu.daijia.model.vo.customer.CustomerLoginVo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class CustomerServiceImpl implements CustomerService {

    @Resource
    private CustomerInfoFeignClient client;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public String login(String code) {
        // 1. 远程调用获取customerId
        Result<Long> result = client.login(code);
        // result 是否正常返回
        if (result.getCode() != 200) {
            throw new GuiguException(ResultCodeEnum.LOGIN_MOBLE_ERROR);
        }
        Long customerId = result.getData();
        // 2. 判断customerId是否正确
        if (customerId == null) {
            throw new GuiguException(ResultCodeEnum.ACCOUNT_ERROR);
        }
        // 3. 根据openId生成jwt
        String jwt = JwtUtil.generateJWT(customerId.toString());

        // 4. 将jwt存入redis
        stringRedisTemplate.opsForValue().set(RedisConstant.USER_LOGIN_KEY_PREFIX + jwt,
                customerId.toString(),
                RedisConstant.USER_LOGIN_KEY_TIMEOUT, TimeUnit.SECONDS);
        // 5. 返回jwt
        return jwt;
    }

    @Override
    public CustomerLoginVo getCustomerLoginInfo(String token) {
        // 0. 获取customerId，前面登陆校验customerId已经放到了ThreadLocal中了
        Long customerId = AuthContextHolder.getUserId();
        // 1. 远程调用
        Result<CustomerLoginVo> result = client.getCustomerLoginInfo(customerId);
        if (result.getCode() != 200) {
            throw new GuiguException(ResultCodeEnum.ACCOUNT_ERROR);
        }
        // 2. 得到CustomerLoginVo
        CustomerLoginVo data = result.getData();
        if (ObjectUtils.isEmpty(data)) {
            throw new GuiguException(ResultCodeEnum.ACCOUNT_ERROR);
        }
        return data;
    }
}
